<template>
  <!-- 耗材设备绑定表单弹窗 -->
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    width="30%"
    draggable
    @close="closeDialog"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="160">
      <el-row>
        <el-col :span="24">
          <el-form-item label="物料号" prop="materialId">
            <el-select
              v-model="formData.materialId"
              placeholder="请选择物料号"
              filterable
              clearable
              style="width: 300px"
            >
              <el-option
                v-for="item in materialOptions"
                :key="item.id"
                :label="`${item.materialCode}-${item.materialName}`"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="产品型号" prop="productCode">
            <el-select
              v-model="formData.productCode"
              placeholder="请选择产品型号"
              filterable
              clearable
              style="width: 300px"
            >
              <el-option
                v-for="item in productOptions"
                :key="item.productCode"
                :label="`${item.productCode}-${item.productName}`"
                :value="item.productCode"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="设备" prop="equipCode">
            <el-select
              v-model="formData.equipCode"
              placeholder="请选择设备"
              filterable
              clearable
              style="width: 300px"
              @change="queryEquipPosition"
            >
              <el-option
                v-for="item in equipOptions"
                :key="item.id"
                :label="`${item.equipCode}-${item.equipName}`"
                :value="item.equipCode"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="安装位置" prop="position">
            <el-select
              v-model="formData.position"
              placeholder="请选择安装位置"
              filterable
              clearable
              style="width: 300px"
              :disabled="!formData.equipCode"
            >
              <el-option
                v-for="item in equipPositionList"
                :key="item.id"
                :label="item.position"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="可用寿命" prop="usefulLife">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.usefulLife"
              placeholder="请输入可用寿命"
              clearable
              style="width: 300px"
            >
              <template #append>件</template>
            </el-input>

            <span v-else>{{ formData.usefulLife }}</span>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary";
import { validatePositiveInteger } from "@/utils/commonHooks";
import {
  EquipOptions,
  EquipPositionOptions,
} from "@/views/eam/csm/optionsTypes";
import { useCsmSelectOptionsStore } from "@/views/eam/csm/store/csmSelectOptionsStore";
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "EAMCSMBINDEQUIPMENTADDORUPDATE",
  inheritAttrs: false,
});

const optionsStore = useCsmSelectOptionsStore();
const materialOptions = computed(() => optionsStore.materialOptions);
const productOptions = computed(() => optionsStore.productOptions);
const equipOptions = computed(() => optionsStore.equipOptions);
const equipPositionList = ref<Array<EquipPositionOptions>>([]);

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

const rules = reactive({
  productCode: [
    {
      required: true,
      message: "请选择产品型号",
      trigger: "blur",
    },
  ],
  materialId: [
    {
      required: true,
      message: "请选择物料号",
      trigger: "blur",
    },
  ],
  usefulLife: [
    {
      required: true,
      message: "请输入可用寿命",
      trigger: "blur",
    },
    {
      validator: validatePositiveInteger,
      trigger: "blur",
    },
    {
      max: 9,
      message: "最大值为999999999",
      trigger: "blur",
    },
  ],
  equipCode: [
    {
      required: true,
      message: "请选择设备",
      trigger: "blur",
    },
  ],
  position: [
    {
      required: true,
      message: "请选择安装位置",
      trigger: "blur",
    },
  ],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  productCode: "",
  materialId: "",
  usefulLife: "",
  equipCode: "",
  equipPosition: "",
  position: "",
  enabled: "",
  deleted: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  lastUpdateTime: "",
  equipPositionId: "",
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        productCode,
        materialId,
        usefulLife,
        equipCode,
        equipPosition,
        position,
        enabled,
        deleted,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdatedUserId,
        lastUpdatedUserName,
        lastUpdateTime,
        equipPositionId,
      } = newVal;
      Object.assign(formData, {
        id,
        productCode,
        materialId,
        usefulLife: usefulLife.toString(),
        equipCode,
        equipPosition,
        position,
        enabled,
        deleted,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdatedUserId,
        lastUpdatedUserName,
        lastUpdateTime,
        equipPositionId,
      });
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.productCode = "";
  formData.materialId = "";
  formData.usefulLife = "";
  formData.equipCode = "";
  formData.equipPosition = "";
  formData.enabled = "";
  formData.deleted = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.lastUpdateTime = "";
  formData.equipPositionId = "";
}

const loading = ref(false);

/** 耗材设备绑定保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      const find = equipPositionList.value.find(
        (item) => item.id === formData.position
      );
      formData.equipPositionId = find ? find.id : "";
      formData.equipPosition = find ? find.position : "";
      await request({
        url: "/eam/csmbindequipment/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});

const queryEquipPosition = async () => {
  const find = equipOptions.value.find(
    (item: EquipOptions) => item.equipCode === formData.equipCode
  );
  formData.position = "";
  if (!find) {
    return;
  }
  const { data } = await request({
    url: "/mdm/mdmequipposition/getByEquip",
    method: "GET",
    params: {
      equipId: find.id,
    },
  });
  equipPositionList.value = data;
};

watch(
  () => formData.equipCode,
  () => {
    queryEquipPosition();
  }
);
</script>
